package com.nzw.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.nzw.common.Constant;
import com.nzw.redis.impl.common.RedisTemplate;
import com.nzw.utils.RandCodeUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by XuZhansi on 2017/8/15.
 * 微信登录拦截器
 * 
 */
public class WXInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    HttpSession httpSession;
    
    /**
     *www.dieke.com/member/addUser?a=123&b=321
     * 
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        System.out.println("测试环境："+Constant.TEST);
        if (Constant.TEST){
            httpSession.setAttribute("userId",(long)53);
            return true;}
        Subject subject = SecurityUtils.getSubject();
        System.out.println("登录："+subject.isAuthenticated());
        if (!subject.isAuthenticated()) {
            String contextPath = request.getContextPath();
            String requestUri = request.getRequestURI();
            String queryStr = request.getQueryString();
            //System.out.println("需要转发：" + requestUri + "  sessionId:" + SecurityUtils.getSubject().getSession().getId());
            if (!StringUtils.isEmpty(queryStr))
                requestUri += "?" + queryStr;
            String randomCode = RandCodeUtil.randNumberCodeByCustom("5", 10);
            JSONObject jsonObject = new JSONObject();
            /**
             * 存入授权成功后要跳转的页面
             */
            jsonObject.put("url", requestUri.substring(contextPath.length()));

            String recomemder = request.getParameter("oid");//推荐者身份
            if (recomemder != null)
                jsonObject.put("oid", recomemder);
            redisTemplate.setex("state:" + randomCode, 600, jsonObject.toJSONString());//保存回调成功后跳转url
             //没有登录过，需要进行授权，转发到用户授权页
            request.getRequestDispatcher("/wx/userAuthorize?state=" + randomCode).forward(request, response);
            return false;
        }
        //登录过，不再需要进行授权
        return true;
    }
    
    
    
    //处理请求完成之后，生成视图之前不进行操作  
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
